﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SeDuce.DAL;
using SeDuce.BLL;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using SeDuce.Model;
using System.Text;

public partial class Management_Products_List : PagerBase
{
    Lazy_Yu<BrandBLL> lazyBrandBLL = new Lazy_Yu<BrandBLL>(() => new BrandBLL());
    public BrandBLL LazyBrandBLL
    {
        get { return this.lazyBrandBLL.Value; }
    }
    Lazy_Yu<ProductBLL> lazyProductBLL = new Lazy_Yu<ProductBLL>(() => new ProductBLL());
    public ProductBLL LazyProductBLL
    {
        get { return this.lazyProductBLL.Value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.BindGridView();
        if (!IsPostBack)
        {
            this.DropDownListBind(this.ddlBrands, this.LazyBrandBLL.GetBrands(), "BrandName", "BrandID");
            this.ddlBrands.Items.Insert(0, new ListItem("请选择...", string.Empty));
        }
    }

    private void BindGridView()
    {
        StringBuilder where = new StringBuilder();
        List<SqlParameter> sp = new List<SqlParameter>();
        Dictionary<string, string> attrs = this.GetAllAttributes();
        foreach (KeyValuePair<string, string> attr in attrs)
        {
            if (!attr.Key.StartsWith("Sort_") && !string.IsNullOrEmpty(attr.Value))
            {
                string key = attr.Key.Split('|')[0];
                string option = attr.Key.Split('|')[1];
                string format = string.Empty;
                switch (option)
                {
                    case "eq":
                        format = " AND {0}=@{1}";
                        sp.Add(new SqlParameter("@" + key.Split('.')[1], attr.Value));
                        break;
                    case "like":
                        format = " AND {0} like @{1}";
                        sp.Add(new SqlParameter("@" + key.Split('.')[1], "%" + attr.Value + "%"));
                        break;
                    default:
                        break;
                }
                where.Append(string.Format(format, key, key.Split('.')[1]));
            }
        }

        List<SortField> sortFields = new List<SortField>();
        if(!string.IsNullOrEmpty(this.GetAttributes("Sort_Field")))
        {
            sortFields.Add(new SortField() { FieldName = this.GetAttributes("Sort_Field"), DESC = (!string.IsNullOrEmpty(this.GetAttributes("Sort_Direct")) ? Convert.ToBoolean(this.GetAttributes("Sort_Direct")) : false) });
        }
        sortFields.Add(new SortField() { FieldName = "Date", DESC = true });


        this.RegistrPager(this.GridView1, this.rptPageFliper, 7, this.FillPageMoudleWithParams(20, SeDuce.DAL.ProductDAL.sqlGetProducts + where.ToString(), sp.ToArray(), sortFields));

        this.txtPageNum.Visible = (this.TotalPage(this.rptPageFliper.UniqueID) > 1);
    }

    protected void lbtnADD_Click(object sender, EventArgs e)
    {
        Response.Redirect("Add.aspx");
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow row = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
        if (row.RowType == DataControlRowType.DataRow)
        {
            string strID = ((Label)this.GridView1.Rows[row.RowIndex].Cells[1].FindControl("lblID")).Text.Trim();
            if (e.CommandName == "DEL")
            {
                string oldLogo = ((HiddenField)this.GridView1.Rows[row.RowIndex].Cells[15].FindControl("hidLogo")).Value.Trim();
                string oldLogo174 = oldLogo.Split('.')[0] + "_174_174." + oldLogo.Split('.')[1];
                string oldLogo100 = oldLogo.Split('.')[0] + "_100_100." + oldLogo.Split('.')[1];
                this.LazyProductBLL.DeleteProduct(strID.ToInt());
                if (File.Exists(Server.MapPath(oldLogo)))
                {
                    File.Delete(Server.MapPath(oldLogo));
                }
                if (File.Exists(Server.MapPath(oldLogo174)))
                {
                    File.Delete(Server.MapPath(oldLogo174));
                }
                if (File.Exists(Server.MapPath(oldLogo100)))
                {
                    File.Delete(Server.MapPath(oldLogo100));
                }
                this.BindPage(this.rptPageFliper.UniqueID, 1);
            }
        }
        else
        {
            if (e.CommandName == "SORT")
            {
                bool desc = Convert.ToBoolean(!string.IsNullOrEmpty(this.GetAttributes("Sort_Direct"))?this.GetAttributes("Sort_Direct"):"false");
                this.AddAttributes("Sort_Field", e.CommandArgument.ToString());
                if (e.CommandArgument.ToString() == this.GetAttributes("Sort_Field"))
                {
                    desc = !desc;
                }
                this.AddAttributes("Sort_Direct", desc.ToString());
                this.AddAttributes("Sort_ControlID", ((LinkButton)e.CommandSource).ID);

                this.BindGridView();
                this.BindPage(this.rptPageFliper.UniqueID, 1);
            }
        }
    }

    protected string GetStatus(int statusID)
    {
        return new Utils().productStatus[statusID - 1].Name;
    }
    protected void ddlBrands_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.AddAttributes("TbProdcutBrand_Map.BrandID|eq", this.ddlBrands.SelectedValue);
        this.BindGridView();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            if (!string.IsNullOrEmpty(this.GetAttributes("Sort_ControlID")))
            {
                LinkButton lbtnHeader = (LinkButton)e.Row.FindControl(this.GetAttributes("Sort_ControlID"));
                lbtnHeader.Text = Convert.ToBoolean(this.GetAttributes("Sort_Direct")) ? lbtnHeader.Text + HttpUtility.HtmlEncode("↓") : lbtnHeader.Text + HttpUtility.HtmlEncode("↑");
            }
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlSeq = (DropDownList)e.Row.FindControl("ddlSeq");
            DataRowView row = (DataRowView)e.Row.DataItem;
            string seq = row["Seq"] != DBNull.Value ? row["Seq"].ToString() : string.Empty;
            this.DropDownListFixByValue(ddlSeq, seq);
            switch (seq)
            {
                case "2"://置顶
                    ddlSeq.BackColor = System.Drawing.Color.OrangeRed;
                    break;
                case "0"://置底
                    ddlSeq.BackColor = System.Drawing.Color.DarkGreen;
                    break;
                default:
                    ddlSeq.BackColor = System.Drawing.Color.DarkGray;
                    break;
            }

            DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatus");
            string status = row["Status"] != DBNull.Value ? row["Status"].ToString() : string.Empty;
            this.DropDownListFixByValue(ddlStatus, status);
            switch (status)
            {
                case "1"://现货
                    ddlStatus.BackColor = System.Drawing.Color.Orange;
                    break;
                case "2"://预订
                    ddlStatus.BackColor = System.Drawing.Color.LightBlue;
                    break;
                case "3"://活动中
                    ddlStatus.BackColor = System.Drawing.Color.DarkRed;
                    break;
                case "4"://已售完
                    ddlStatus.BackColor = System.Drawing.Color.DarkGray;
                    break;
                default:
                    ddlStatus.BackColor = System.Drawing.Color.DarkGray;
                    break;
            }

            //读取Brands
            Label lblID = (Label)e.Row.FindControl("lblID");
            Label lblBrandName = (Label)e.Row.FindControl("lblBrandName");
            DataTable dtBrands = this.LazyProductBLL.GetBrandsByProductID(lblID.Text.ToInt());
            if (dtBrands.Rows.Count > 0)
            {
                List<Brand> brands = dtBrands.ToList<Brand>();
                lblBrandName.Text = string.Join("/", (from b in brands select b.BrandName).ToArray<String>());
            }

            //读取Types
            Label lblTypeName = (Label)e.Row.FindControl("lblTypeName");
            DataTable dtTypes = this.LazyProductBLL.GetTypesByProductID(lblID.Text.ToInt());
            if (dtTypes.Rows.Count > 0)
            {
                List<SeDuce.Model.Type> types = dtTypes.ToList<SeDuce.Model.Type>();
                lblTypeName.Text = string.Join("/", (from t in types select t.TypeName).ToArray<String>());
            }
        }
    }

    protected void ddlSeq_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlSeq = ((DropDownList)sender);
        GridViewRow row = (GridViewRow)ddlSeq.Parent.Parent;
        string seq = ddlSeq.SelectedValue;
        int intProductID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
        DataTable dtProduct = this.LazyProductBLL.GetProductByProductID(intProductID);
        if (dtProduct.Rows.Count > 0)
        {
            bool result = this.LazyProductBLL.UpdateProduct(new Product()
            {
                ProductID = dtProduct.Rows[0]["ProductID"].ToString().ToInt(),
                ProductName = dtProduct.Rows[0]["ProductName"].ToString(),
                UnitPrice = Convert.ToDecimal(dtProduct.Rows[0]["UnitPrice"]),
                SalePrice = Convert.ToDecimal(dtProduct.Rows[0]["SalePrice"]),
                Size = dtProduct.Rows[0]["Size"].ToString(),
                Color = dtProduct.Rows[0]["Color"].ToString(),
                Description = dtProduct.Rows[0]["Description"].ToString(),
                Date = DateTime.Now,
                Status = dtProduct.Rows[0]["Status"].ToString().ToInt(),
                ImageBig = dtProduct.Rows[0]["ImageBig"].ToString(),
                Image174 = dtProduct.Rows[0]["Image174"].ToString(),
                Image100 = dtProduct.Rows[0]["Image100"].ToString(),
                UnitPriceUS = Convert.ToDecimal(dtProduct.Rows[0]["UnitPriceUS"]),
                SalePriceUS = Convert.ToDecimal(dtProduct.Rows[0]["SalePriceUS"]),
                UnitPriceJP = Convert.ToDecimal(dtProduct.Rows[0]["UnitPriceJP"]),
                SalePriceJP = Convert.ToDecimal(dtProduct.Rows[0]["SalePriceJP"]),
                Seq = seq.ToInt()
            }, null, null);
            if (result)
            {
                switch (seq)
                {
                    case "2"://置顶
                        ddlSeq.BackColor = System.Drawing.Color.OrangeRed;
                        break;
                    case "0"://置底
                        ddlSeq.BackColor = System.Drawing.Color.DarkGreen;
                        break;
                    default:
                        ddlSeq.BackColor = System.Drawing.Color.DarkGray;
                        break;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
            }
        }
    }

    protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddlStatus = ((DropDownList)sender);
        GridViewRow row = (GridViewRow)ddlStatus.Parent.Parent;
        string status = ddlStatus.SelectedValue;
        int intProductID = ((Label)row.Cells[1].FindControl("lblID")).Text.ToInt();
        DataTable dtProduct = this.LazyProductBLL.GetProductByProductID(intProductID);
        if (dtProduct.Rows.Count > 0)
        {
            bool result = this.LazyProductBLL.UpdateProduct(new Product()
            {
                ProductID = dtProduct.Rows[0]["ProductID"].ToString().ToInt(),
                ProductName = dtProduct.Rows[0]["ProductName"].ToString(),
                UnitPrice = Convert.ToDecimal(dtProduct.Rows[0]["UnitPrice"]),
                SalePrice = Convert.ToDecimal(dtProduct.Rows[0]["SalePrice"]),
                Size = dtProduct.Rows[0]["Size"].ToString(),
                Color = dtProduct.Rows[0]["Color"].ToString(),
                Description = dtProduct.Rows[0]["Description"].ToString(),
                Date = DateTime.Now,
                Status = status.ToInt(),
                ImageBig = dtProduct.Rows[0]["ImageBig"].ToString(),
                Image174 = dtProduct.Rows[0]["Image174"].ToString(),
                Image100 = dtProduct.Rows[0]["Image100"].ToString(),
                UnitPriceUS = Convert.ToDecimal(dtProduct.Rows[0]["UnitPriceUS"]),
                SalePriceUS = Convert.ToDecimal(dtProduct.Rows[0]["SalePriceUS"]),
                UnitPriceJP = Convert.ToDecimal(dtProduct.Rows[0]["UnitPriceJP"]),
                SalePriceJP = Convert.ToDecimal(dtProduct.Rows[0]["SalePriceJP"]),
                Seq = Convert.ToInt32(dtProduct.Rows[0]["Seq"])
            }, null, null);
            if (result)
            {
                switch (status)
                {
                    case "1"://现货
                        ddlStatus.BackColor = System.Drawing.Color.Orange;
                        break;
                    case "2"://预订
                        ddlStatus.BackColor = System.Drawing.Color.LightBlue;
                        break;
                    case "3"://活动中
                        ddlStatus.BackColor = System.Drawing.Color.DarkRed;
                        break;
                    case "4"://已售完
                        ddlStatus.BackColor = System.Drawing.Color.DarkGray;
                        break;
                    default:
                        ddlStatus.BackColor = System.Drawing.Color.DarkGray;
                        break;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Key6", "javascript:" + string.Format("alert('{0}');", "保存时发生错误!请重试..."), true);
            }
        }
    }

    protected void txtPageNum_TextChanged(object sender, EventArgs e)
    {
        int num = 0;
        if (int.TryParse(this.txtPageNum.Text.Trim(), out num))
        {
            if (num <= this.TotalPage(this.rptPageFliper.UniqueID) && num > 0)
            {
                this.BindGridView();
                this.BindPage(this.rptPageFliper.UniqueID, num);
            }
        }
    }
    protected void lbtnSearch_Click(object sender, EventArgs e)
    {
        this.AddAttributes("TbProduct.ProductName|like", this.txtSearchName.Text.Trim());
        this.BindGridView();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }
    protected void lbtnBack_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> attrs = this.GetAllAttributes();
        List<string> keys = new List<string>();
        foreach (KeyValuePair<string, string> attr in attrs)
        {
            if (!attr.Key.StartsWith("Sort_") && !string.IsNullOrEmpty(attr.Value))
            {
                keys.Add(attr.Key);
            }
        }
        keys.ForEach(k => this.RemoveAttributes(k));

        this.BindGridView();
        this.BindPage(this.rptPageFliper.UniqueID, 1);
    }
}